local blaze = require "blaze"
local app = require "app"

local log = app.logging.get("Header")

local M = app.ui.element()

M.store_watchers = {
    level_bonus = {
        ["等级奖励变更"] = function(self, store, state, args)
            self.level_bonus_txt.text = string.format("LV %d", state.level)
        end
    }
}

function M:ctor()
    local OnlineBonus = require "club.threecard.casinolib.ui.gamelobby.OnlineBonus"
    self.online_bonus = OnlineBonus.new()
end

function M:on_injected(bind)
    bind("button.click", self.shop_btn, self.on_shop)
    bind("button.click", self.back_btn, self.on_back)
    bind("shortcut.escape", self.back_btn.gameObject, self.on_back)
    bind("button.click", self.level_bonus_btn, self.on_level_bonus)
    bind("gameobject.element", self.online_bonus_obj, self.online_bonus)

    if not app.version.support("支付") then
        self.shop_btn.gameObject:SetActive(false)
    end
end

function M:on_shop()
    app.router.push("/shop")
end

function M:on_back()
    if app.router.stack():count() > 1 then
        app.router.back()
    else
        app.game.exit()
    end
end

local function parse_rewards_desc(rewards)
    local buffer = {}
    for _, reward in ipairs(rewards) do
        table.insert(buffer, app.i18n.text(string.format("item%d:name", reward.id)))
        table.insert(buffer, ": ")
        table.insert(buffer, reward.qty)
        table.insert(buffer, "\n")
    end
    buffer[#buffer] = nil
    return table.concat(buffer)
end

function M:on_level_bonus()
    local level_bonus = app.store.level_bonus.state
    local tip = app.i18n.text("milestone level:tip", {
        level = level_bonus.level,
        rewards = parse_rewards_desc(level_bonus.rewards)
    })
    app.tooltip.show(tip, self.level_bonus_tooltip.position)
end

return M